import React, { useCallback, useMemo } from "react"
import "./App.css"
import { connect } from "react-redux"
import { bindActionCreators } from "redux"

import Header from "../common/Header.jsx"
import DepartDate from "./DepartDate.jsx"
import HighSpeed from "./HighSpeed.jsx"
import Journey from "./Journey.jsx"
import Submit from "./Submit.jsx"

import CitySelector from "../common/CitySelector.jsx"
import DateSelector from "../common/DateSelector.jsx"

import { h0 } from "../common/fp"

import {
  exchangeFromTo,
  showCitySelector,
  hideCitySelector,
  fetchCityData,
  setSelectedCity,
  showDateSelector,
  hideDateSelector,
  setDepartDate,
  toggleHighSpeed,
} from "./store/actions"

function App(props) {
  const {
    from,
    to,
    isCitySelectorVisible,
    isDateSelectorVisible,
    cityData,
    isLoadingCityData,
    highSpeed,
    dispatch,
    departDate,
  } = props

  const onBack = useCallback(() => {
    window.history.back()
  }, [])

  const journeyCallbacks = useMemo(() => {
    return bindActionCreators(
      {
        exchangeFromTo,
        showCitySelector,
      },
      dispatch
    )
  }, [])

  const citySelectorCallbacks = useMemo(() => {
    return bindActionCreators(
      {
        onBack: hideCitySelector,
        fetchCityData,
        onSelect: setSelectedCity,
      },
      dispatch
    )
  }, [])

  const departDateCallbacks = useMemo(() => {
    return bindActionCreators(
      {
        onClick: showDateSelector,
      },
      dispatch
    )
  }, [])

  const highSpeedCallbacks = useMemo(() => {
    return bindActionCreators(
      {
        toggle: toggleHighSpeed,
      },
      dispatch
    )
  }, [])

  const dateSelectorCallbacks = useMemo(() => {
    return bindActionCreators(
      {
        onBack: hideDateSelector,
      },
      dispatch
    )
  }, [])

  const onSelectDate = useCallback((day) => {
    if (!day) {
      return
    }

    if (day < h0()) {
      return
    }

    dispatch(setDepartDate(day))
    dispatch(hideDateSelector())
  }, [])

  return (
    <div className="App">
      <div className="header-wrapper">
        <Header title="火车票" onBack={onBack} />
      </div>
      <form action="./query.html" className="form">
        <Journey from={from} to={to} {...journeyCallbacks} />
        <DepartDate time={departDate} {...departDateCallbacks} />
        <HighSpeed highSpeed={highSpeed} {...highSpeedCallbacks} />
        <Submit />
      </form>
      <CitySelector
        show={isCitySelectorVisible}
        cityData={cityData}
        isLoading={isLoadingCityData}
        {...citySelectorCallbacks}
      />
      <DateSelector
        show={isDateSelectorVisible}
        onSelect={onSelectDate}
        {...dateSelectorCallbacks}
      />
    </div>
  )
}

const mapStateToProps = (state) => {
  return state
}

const mapDispatchToProps = (dispatch) => {
  return { dispatch }
}

export default connect(mapStateToProps, mapDispatchToProps)(App)
